package com.bnlr.lrparking.appui.mine.recentparkrecord;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.base.BaseResponse;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.model.UpImgM;
import com.bnlr.lrparking.model.UploadGoodsBean;
import com.bnlr.lrparking.util.BitmapHelper;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.Config;
import com.bnlr.lrparking.util.DbTOPxUtils;
import com.bnlr.lrparking.util.FileUtil;
import com.bnlr.lrparking.util.MyGridView;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.bumptech.glide.Glide;
import com.yolanda.nohttp.NoHttp;
import com.zzti.fengyongge.imagepicker.PhotoPreviewActivity;
import com.zzti.fengyongge.imagepicker.PhotoSelectorActivity;
import com.zzti.fengyongge.imagepicker.model.PhotoModel;
import com.zzti.fengyongge.imagepicker.util.CommonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * description: 提交小票页面
 * SubmitReceiptActivity class
 *
 * @author : Licy
 * @date : 2018/12/26
 */
public class SubmitReceiptActivity extends BaseActivity {

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.tv_nav_right)
    TextView tvNavRight;
    @BindView(R.id.iv_nav_back)
    ImageView ivNavBack;
    @BindView(R.id.rela_nav_back)
    RelativeLayout relaNavBack;
    @BindView(R.id.iv_nav_right)
    ImageView ivNavRight;
    @BindView(R.id.my_receipt_GV)
    MyGridView my_imgs_GV;
    @BindView(R.id.btn_submit_receipts)
    TextView submitReceipts;

    @BindView(R.id.img_upload_result)
    ImageView imgUploadResult;
    @BindView(R.id.tv_upload_result)
    TextView tvUploadResult;
    @BindView(R.id.btn_re_upload)
    Button btnReUpload;
    @BindView(R.id.ll_result_view)
    LinearLayout llResultView;

    private ArrayList<UploadGoodsBean> img_uri = new ArrayList<UploadGoodsBean>();
    private List<PhotoModel> single_photos = new ArrayList<PhotoModel>();
    private List<String> urlArray = new ArrayList<>();
    private int screen_widthOffset;
    private GridImgAdapter gridImgsAdapter;
    private String path = "";
    private String orderNum;

    private Context mContext;
    /**
     * 上传结果
     * true  成功
     * false 失败
     */
    private boolean result = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submitreceipt);
        ButterKnife.bind(this);
        mContext = this;
        orderNum = getIntent().getStringExtra("orderNum");

        initView();
        initListener();
    }

    public void initView() {
        tvNavTitle.setText("上传");

        Config.ScreenMap = Config.getScreenSize(this, this);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screen_widthOffset = (display.getWidth() - (3 * DbTOPxUtils.dip2px(this, 2))) / 3;

    }

    public void initListener() {

        gridImgsAdapter = new GridImgAdapter();
        my_imgs_GV.setAdapter(gridImgsAdapter);
        if (img_uri.size() < 3) {
            img_uri.add(null);
        }
        gridImgsAdapter.notifyDataSetChanged();

        submitReceipts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitReceiptsToServer();
            }
        });

        btnReUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (result) {
                    tvNavTitle.setText("上传");
                    llResultView.setVisibility(View.GONE);
                    finish();
                } else {
                    submitReceiptsToServer();
                }
            }
        });

    }

    class GridImgAdapter extends BaseAdapter implements ListAdapter {

        @Override
        public int getCount() {
            return img_uri.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(SubmitReceiptActivity.this).inflate(R.layout.activity_addstory_img_item, null);
            ViewHolder holder;
            if (convertView != null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(SubmitReceiptActivity.this).inflate(R.layout.activity_addstory_img_item, null);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.add_IB = (ImageView) convertView.findViewById(R.id.add_IB);
            holder.delete_IV = (ImageView) convertView.findViewById(R.id.delete_IV);
            AbsListView.LayoutParams param = new AbsListView.LayoutParams(screen_widthOffset, screen_widthOffset);
            convertView.setLayoutParams(param);
            if (img_uri.get(position) == null) {
                holder.delete_IV.setVisibility(View.GONE);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(SubmitReceiptActivity.this, PhotoSelectorActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        intent.putExtra("limit", 3 - (img_uri.size() - 1));
                        startActivityForResult(intent, 0);
                    }
                });
            } else {
                Glide.with(SubmitReceiptActivity.this).load(img_uri.get(position).getUrl()).into(holder.add_IB);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.delete_IV.setOnClickListener(new View.OnClickListener() {
                    private boolean is_addNull;

                    @Override
                    public void onClick(View arg0) {
                        is_addNull = true;
                        img_uri.remove(position);
                        urlArray.remove(position);
                        single_photos.remove(position);
                        for (int i = 0; i < img_uri.size(); i++) {
                            if (img_uri.get(i) == null) {
                                is_addNull = false;
                                continue;
                            }
                        }
                        if (is_addNull) {
                            img_uri.add(null);
                        }
                        //FileUtils.DeleteFolder(img_url);//删除在emulate/0文件夹生成的图片
                        gridImgsAdapter.notifyDataSetChanged();
                    }
                });
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("photos", (Serializable) single_photos);
                        bundle.putInt("position", position);
                        bundle.putBoolean("isSave", false);
                        bundle.putBoolean("isNet", true);
                        CommonUtils.launchActivity(SubmitReceiptActivity.this, PhotoPreviewActivity.class, bundle);
                    }
                });

            }
            return convertView;
        }

        class ViewHolder {
            ImageView add_IB;
            ImageView delete_IV;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");
                    if (img_uri.size() > 0) {
                        img_uri.remove(img_uri.size() - 1);
                    }
                    for (int i = 0; i < paths.size(); i++) {
                        if (FileUtil.fileExists(paths.get(i))) {
                            img_uri.add(new UploadGoodsBean(paths.get(i), false));
                            //上传参数
                            path = path + CommonUtil.bitmapToBase64(BitmapHelper.getImage(paths.get(i), 200))
                                    + "|";
                        }
                    }
                    if (path.length() > 0) {
                        path = path.substring(0, path.length() - 1);
                        //上传图片
                        sendImage(path, "2");

                        if (img_uri.size() < 3) {
                            img_uri.add(null);
                        }
                        gridImgsAdapter.notifyDataSetChanged();
                    }
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 发送图片到服务器
     *
     * @param img       图片地址
     * @param stallType 类型
     */
    private void sendImage(String img, String stallType) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP_UpImg, LrConstant.POST);
            mRequest.add("action", "FileUploadImage");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("type", stallType);
            mRequest.add("img", img);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<UpImgM>(baseContext, true, UpImgM.class) {
                        @Override
                        public void doWork(UpImgM data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (TextUtils.equals("1", code)) {
                                    String url = obj.getString("data");
                                    String[] arr = url.split(",");
                                    for (int i = 0; i < arr.length; i++) {
                                        urlArray.add(arr[i]);
                                    }
                                    for (int i = 0; i < urlArray.size(); i++) {
                                        PhotoModel photoModel = new PhotoModel();
                                        photoModel.setOriginalPath(urlArray.get(i));
                                        photoModel.setChecked(true);
                                        single_photos.add(photoModel);
                                    }
                                    path = "";
                                } else {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }


    /**
     * 绑定图片与订单号
     */
    private void submitReceiptsToServer() {

        StringBuffer photoPath = new StringBuffer();

        for (int i = 0; i < single_photos.size(); i++) {
            photoPath.append(single_photos.get(i).getOriginalPath());
            if (i < (single_photos.size() - 1)) {
                photoPath.append(",");
            }
        }

        LogUtils.d("photoPath", photoPath.toString());

        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "UploadReceipt");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("photo", photoPath.toString().trim());
            mRequest.add("orderNum", orderNum);

            CallServer.getRequestInstance().add(
                    mContext,
                    mRequest,
                    new CustomHttpListener<BaseResponse>(mContext, true, BaseResponse.class) {

                        @Override
                        public void doWork(BaseResponse data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            LogUtils.d(obj.toString());
                            try {
                                if (isSucceed) {
                                    if ((obj.getInt("errorCode") == 0) && code.equals("1")) {
                                        // 上传成功
                                        result = true;
                                    } else {
                                        // 上传失败
                                        result = false;
                                    }
                                } else {
                                    // 上传失败
                                    result = false;
                                }
                                refreshView(result);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void refreshView(boolean result) {
        llResultView.setVisibility(View.VISIBLE);
        tvNavTitle.setText("上传结果");
        if (result) {
            imgUploadResult.setImageResource(R.mipmap.pay_seccess);
            tvUploadResult.setText("小票上传成功，我们将会在1~3个工作日\n返回审核结果，请耐心等待！");
            btnReUpload.setText("完成");
        } else {
            imgUploadResult.setImageResource(R.mipmap.icon_pay_fail);
            tvUploadResult.setText("上传失败！");
            btnReUpload.setText("重新上传");
        }
    }


}
